package com.lottery.common.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.util.List;
import java.util.Map;

public class ConnectionUrlUtil {
	public static String sendPost(String url, String parameter) {
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte contentbyte[] = parameter.toString().getBytes();
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 鐠佸墽鐤嗙拠閿嬬湴缁鐎�
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			// 鐠佸墽鐤嗙悰銊ュ礋闂�灝瀹�
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			// 鐠佸墽鐤嗘妯款吇鐠囶叀鈻�
			conn.setRequestProperty("Content-Language", "en-US");// zh-CN娴狅綀銆冩稉顓炴禇
																	// 姒涙顓绘稉铏圭法瀵繗瀚崇拠锟�
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("contentType", "utf-8");
			// 鏉╃偞甯存稉缁樻簚閻ㄥ嫯绉撮弮鑸垫闂傝揪绱欓崡鏇氱秴閿涙碍顕犵粔鎺炵礆
			conn.setConnectTimeout(60000);
			// 娴犲簼瀵岄張楦款嚢閸欐牗鏆熼幑顔炬畱鐡掑懏妞傞弮鍫曟？閿涘牆宕熸担宥忕窗濮ｎ偆顬�
			conn.setReadTimeout(60000);
			// Post 鐠囬攱鐪版稉宥堝厴娴ｈ法鏁ょ紓鎾崇摠
			conn.setUseCaches(false);
			// 鐠佸墽鐤嗛弰顖氭儊娴犲穻ttpUrlConnection鐠囪鍙嗛敍宀勭帛鐠併倖鍎忛崘鍏哥瑓閺勭椂rue;
			conn.setDoInput(true);
			// 鐠佸墽鐤嗛弰顖氭儊閸氭吋ttpUrlConnection鏉堟挸鍤敍灞芥礈娑撻缚绻栨稉顏呮Цpost鐠囬攱鐪伴敍灞藉棘閺佹媽顪呴弨鎯ф躬
			// 2
			// http濮濓絾鏋冮崘鍜冪礉閸ョ姵顒濋棁锟筋渽鐠佸彞璐焧rue, 姒涙顓婚幆鍛枌娑撳妲竑alse;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
			bWriter.write(parameter.toString());
			bWriter.flush();
			bWriter.close();
			// 鐠嬪啰鏁ttpURLConnection鏉╃偞甯寸�纭呰杽閻ㄥ埀etInputStream()閸戣姤鏆�
			// 鐏忓棗鍞寸�妯肩处閸愭彃灏稉顓炵殱鐟佸懎銈介惃鍕暚閺佸娈慔TTP鐠囬攱鐪伴悽鍨瀮閸欐垿锟介崚鐗堟箛閸旓紕顏妴锟�
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1)
					buffer.append((char) i);
			}
			in.close();

			// 濮濄倖鏌熷▔鏇熸Ц閻⑩墽eader鐠囪褰嘊ufferedReader reader = new
			// BufferedReader(new
			// InputStreamReader( connection.getInputStream()));
			result = new String(buffer.toString().getBytes("iso-8859-1"), "UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println(ex.getLocalizedMessage());
			result = "";
		}
		return result;
	}

	public static String sendPostByJson(String url, String json) {
		String result = "";
		try {
			URL u0 = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte contentbyte[] = json.toString().getBytes();
			conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			// 设置文件类型:json
			conn.setRequestProperty("Content-Type","application/json; charset=UTF-8");
			// 设置文件长度
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			
			conn.setRequestProperty("Content-Language", "en-US");// zh-CN娴狅綀銆冩稉顓炴禇
																	// 姒涙顓绘稉铏圭法瀵繗瀚崇拠锟�
			conn.setRequestProperty("Accept-Charset", "utf-8");
			conn.setRequestProperty("contentType", "utf-8");
			// 超时时间
			conn.setConnectTimeout(60000);
			// 娴犲簼瀵岄張楦款嚢閸欐牗鏆熼幑顔炬畱鐡掑懏妞傞弮鍫曟？閿涘牆宕熸担宥忕窗濮ｎ偆顬�
			conn.setReadTimeout(60000);
			// Post 鐠囬攱鐪版稉宥堝厴娴ｈ法鏁ょ紓鎾崇摠
			conn.setUseCaches(false);
			// 鐠佸墽鐤嗛弰顖氭儊娴犲穻ttpUrlConnection鐠囪鍙嗛敍宀勭帛鐠併倖鍎忛崘鍏哥瑓閺勭椂rue;
			conn.setDoInput(true);
			// 鐠佸墽鐤嗛弰顖氭儊閸氭吋ttpUrlConnection鏉堟挸鍤敍灞芥礈娑撻缚绻栨稉顏呮Цpost鐠囬攱鐪伴敍灞藉棘閺佹媽顪呴弨鎯ф躬
			// 2
			// http濮濓絾鏋冮崘鍜冪礉閸ョ姵顒濋棁锟筋渽鐠佸彞璐焧rue, 姒涙顓婚幆鍛枌娑撳妲竑alse;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
			bWriter.write(json.toString());
			bWriter.flush();
			bWriter.close();
			// 鐠嬪啰鏁ttpURLConnection鏉╃偞甯寸�纭呰杽閻ㄥ埀etInputStream()閸戣姤鏆�
			// 鐏忓棗鍞寸�妯肩处閸愭彃灏稉顓炵殱鐟佸懎銈介惃鍕暚閺佸娈慔TTP鐠囬攱鐪伴悽鍨瀮閸欐垿锟介崚鐗堟箛閸旓紕顏妴锟�
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1)
					buffer.append((char) i);
			}
			in.close();

			// 濮濄倖鏌熷▔鏇熸Ц閻⑩墽eader鐠囪褰嘊ufferedReader reader = new
			// BufferedReader(new
			// InputStreamReader( connection.getInputStream()));
			result = new String(buffer.toString().getBytes("iso-8859-1"), "UTF-8");
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println(ex.getLocalizedMessage());
			result = "";
		}
		return result;
	}
	
	/**
	 * post鎻愪氦
	 * 
	 * @param url
	 *            鎺ユ敹鐨剈rl
	 * @param parameter
	 *            鎺ユ敹鐨勫弬鏁�
	 * @return 杩斿洖缁撴灉
	 */
	public static String sendPostTest(String url, String parameter, String ip) {
		String result = "";
		HttpURLConnection conn = null;
		try {
			URL u0 = new URL(url);

			conn = (HttpURLConnection) u0.openConnection();
			conn.setRequestMethod("POST");
			byte contentbyte[] = parameter.toString().getBytes();
			// 璁剧疆琛ㄥ崟闀垮害
			conn.setRequestProperty("Content-Length", (new StringBuilder()).append(contentbyte.length).toString());
			// 杩炴帴涓绘満鐨勮秴鏃舵椂闂达紙鍗曚綅锛氭绉掞級
			conn.setConnectTimeout(60000);
			// 浠庝富鏈鸿鍙栨暟鎹殑瓒呮椂鏃堕棿锛堝崟浣嶏細姣)
			conn.setReadTimeout(60000);
			// Post 璇锋眰涓嶈兘浣跨敤缂撳瓨
			conn.setUseCaches(false);
			// 璁剧疆鏄惁浠巋ttpUrlConnection璇诲叆锛岄粯璁ゆ儏鍐典笅鏄痶rue;
			conn.setDoInput(true);
			// 璁剧疆鏄惁鍚慼ttpUrlConnection杈撳嚭锛屽洜涓鸿繖涓槸post璇锋眰锛屽弬鏁拌鏀惧湪 2
			// http姝ｆ枃鍐咃紝鍥犳闇�璁句负true, 榛樿鎯呭喌涓嬫槸false;
			conn.setDoOutput(true);
			BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
			bWriter.write(parameter.toString());
			bWriter.flush();
			bWriter.close();
			// 璋冪敤HttpURLConnection杩炴帴瀵硅薄鐨刧etInputStream()鍑芥暟,
			// 灏嗗唴瀛樼紦鍐插尯涓皝瑁呭ソ鐨勫畬鏁寸殑HTTP璇锋眰鐢垫枃鍙戦�鍒版湇鍔＄銆�
			InputStream in = conn.getInputStream();
			StringBuffer buffer = new StringBuffer();
			for (int i = 0; i != -1;) {
				i = in.read();
				if (i != -1)
					buffer.append((char) i);
			}
			in.close();

			// 姝ゆ柟娉曟槸鐢≧eader璇诲彇BufferedReader reader = new BufferedReader(new
			// InputStreamReader( connection.getInputStream()));
			result = new String(buffer.toString().getBytes("iso-8859-1"), "UTF-8");
		} catch (Exception ex) {
			System.out.println(ex);
			result = "";
		}
		return result;
	}

	public static String rest(String serviceUrl, String parameter, String restMethod) {
		StringBuffer sb = new StringBuffer();

		try {
			URL url = new URL(serviceUrl);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();

			con.setConnectTimeout(60 * 1000);
			con.setRequestMethod(restMethod);

			if (!"GET".equals(restMethod)) {
				con.setDoOutput(true);
				if (!"DELETE".equals(restMethod)) {

					OutputStream os = con.getOutputStream();
					os.write(parameter.getBytes("utf-8"));
					os.close();
					InputStream in = con.getInputStream();
					BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
					String line = "";
					while ((line = br.readLine()) != null) {
						sb.append(line);
					}
				}
			} else {
				InputStream in = con.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
				String line = "";
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			}
			// System.out.println(con.getResponseCode() + ":"
			// + con.getResponseMessage());

			// return sb.toString();
			return con.getResponseMessage();

		} catch (Exception e) {
			System.out.println(e);
			return "-1";
		}

	}

	/*
	 * 流获取参数
	 */
	public static String getDecodeParams(HttpServletRequest request) {
		String param = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(),"UTF-8"));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			// 将资料解码
			String reqBody = sb.toString();

			param = URLDecoder.decode(reqBody, HTTP.UTF_8);
			System.out.println("param==" + param);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "";
		}
		return param;
	}


	/*
	 * 流获取参数
	 */
	public static String getParams(HttpServletRequest request) {
		String param = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line = null;
			StringBuilder sb = new StringBuilder();
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			param = sb.toString();
			// 将资料解码

//			String header="{\"phone\": \"PHONE\",    \"token\": \"TOKEN\"} ";
//			if (StringUtils.isNotEmpty(sb.toString())){
//				header="";
//				if (!sb.toString().contains("\"phone\"")){
//					header+=",\"phone\": \"PHONE\"";
//				}
//				if (!sb.toString().contains("\"token\"")){
//					header+=",    \"token\": \"TOKEN\"";
//				}
//				header+="} ";
//			}
//			if (StringUtils.isNotEmpty(request.getHeader("phone"))&&StringUtils.isNotEmpty(request.getHeader("token"))){
//				header=header.replaceAll("PHONE",request.getHeader("phone")).replaceAll("TOKEN",request.getHeader("token"));
//			}
//
//			if (StringUtils.isEmpty(sb.toString())){
//				param=header;
//			}else
//				param = sb.toString().replaceAll("}",header);

			System.out.println("param ==" + param);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return "";
		}
		return param;
	}



	public static void testSend(String json, String url) {
		try {
			String encoderJson = URLEncoder.encode(json);
			StringEntity entity = new StringEntity(encoderJson, HTTP.UTF_8);// 解决中文乱码问题
			entity.setContentType("application/json");
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost method = new HttpPost(url);
			method.setEntity(entity);
			HttpResponse result = httpClient.execute(method);
			String resData = EntityUtils.toString(result.getEntity());
			System.out.println(resData);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			System.out.println("param==" + realUrl);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream() , "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet2(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			System.out.println("param==" + realUrl);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setConnectTimeout(1000);
			connection.setReadTimeout(1000);
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream() , "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}



	/***
	 * 获取 request 中 json 字符串的内容
	 *
	 * @param request
	 * @return : <code>byte[]</code>
	 * @throws IOException
	 */
	public static String getRequestJsonString(HttpServletRequest request)
			throws IOException {
		String submitMehtod = request.getMethod();
		// GET
		if (submitMehtod.equals("GET")) {
			return new String(request.getQueryString().getBytes("iso-8859-1"),"utf-8").replaceAll("%22", "\"");
			// POST
		} else {
			return getRequestPostStr(request);
		}
	}

	/**
	 * 描述:获取 post 请求的 byte[] 数组
	 * <pre>
	 * 举例：
	 * </pre>
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static byte[] getRequestPostBytes(HttpServletRequest request)
			throws IOException {
		int contentLength = request.getContentLength();
		if(contentLength<0){
			return null;
		}
		byte buffer[] = new byte[contentLength];
		for (int i = 0; i < contentLength;) {

			int readlen = request.getInputStream().read(buffer, i,
					contentLength - i);
			if (readlen == -1) {
				break;
			}
			i += readlen;
		}
		return buffer;
	}

	/**
	 * 描述:获取 post 请求内容
	 * <pre>
	 * 举例：
	 * </pre>
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String getRequestPostStr(HttpServletRequest request)
			throws IOException {
		byte buffer[] = getRequestPostBytes(request);
		String charEncoding = request.getCharacterEncoding();
		if (charEncoding == null) {
			charEncoding = "UTF-8";
		}
		return new String(buffer, charEncoding);
	}

	public static String toString(HttpServletRequest request){
        String valueStr = "";
        try {  
            StringBuffer sb = new StringBuffer();
            InputStream is = request.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String s = "";
            while ((s = br.readLine()) != null) {  
                sb.append(s);  
            }  
            valueStr = sb.toString();  
        } catch (IOException e) {
            e.printStackTrace();  
            valueStr = "";  
        }  
        return valueStr;  
	}
	
	public static void main(String[] args) {
		
	}
}
